<?php
namespace classlib\automake;
use classlib\orm;
class model {
	/**
	 * 获取表字段信息的SQL模版
	 * @var string
	 */
	
	static $clomn_sql = 'show full columns from %s';
	/**
	 * 获取数据库所有表结构信息生成ORM
	 * @var string
	 */
	static $table_sql = 'show tables';
	
	/**
	 * 模型对象将生成的模版
	 * @var array
	 */
	static $model     = array(
		'table'		=> '', 
		'prikey'	=> '', 
		'comment'	=> array(),
		'reader'	=> '', 
		'writer'	=> '', 
		'field'	=> array()
	);
	
	/**
	 * 要生成的ORM数据库配置例如acl
	 * @param string $dbinc
	 */
	public static function run($dbinc) {
		self::$model['reader'] = $dbinc.'.reader';
		self::$model['writer'] = $dbinc.'.writer';
		//获取数据库的所有表结构
		$dbquery   = orm::inst(self::$model['writer']);
		$tables    = $dbquery->get_list(self::$table_sql);
		$newmodels = array();
		$modmodels = array();
		$basedir   = COREDIR.'/src/model/'.$dbinc;
		if (!is_dir($basedir)) {
			mkdir($basedir, 0777, true);
		}
		//遍历处理资料
		foreach ($tables as $item) {
			//如果是分表，其后缀是数字的直接跳过
			$table = array_pop($item);
			if (preg_match('/[\d]+$/', $table) || preg_match('/^backup/i', $table)) {
				continue;
			}
			$model = self::$model;
			$model['table'] = $table;
			$start = strpos($table, '_');
			$dir   = $basedir;
			$segns = '';
			if (!$start) {
				$start = -1;
			} else {
				$segns = substr($table, 0, $start);
				$dir  .= '/'.$segns;
				if (!is_dir($dir)) {
					mkdir($dir, 0777, true);
				}
			}
			$fdir  = $dir.'/fields';
			if (!is_dir($fdir)) {
				mkdir($fdir, 0777, true);
			}
			
			$clsname    = substr($table, $start+1);
			$file       = $dir.'/'.$clsname.'.cls.php';
			$column_sql = sprintf(self::$clomn_sql, $table);
			$columns    = $dbquery->get_list($column_sql);
			$maxlen     = 0;
			foreach ($columns as $column) {
				if (isset($column['Key']) && $column['Key'] == 'PRI') {
					$model['prikey'] = $column['Field'];
				}
				$value  = '\'\'';
				if (preg_match('/int/i', $column['Type'])) {
					$value = (isset($column['Default']) && $column['Default'] != NULL)? $column['Default']:'0';
				} else if (preg_match('/float/i', $column['Type'])) {
					$value = (isset($column['Default']) && $column['Default'] != NULL)? $column['Default']:'0.0';
				} else if (preg_match('/double/i', $column['Type'])) {
					$value = (isset($column['Default']) && $column['Default'] != NULL)? $column['Default']:'0.0';
				} else if (preg_match('/decimal/i', $column['Type'])) {
					$value = (isset($column['Default']) && $column['Default'] != NULL)? $column['Default']:'0.0';
				} else if (isset($column['Default']) && $column['Default'] != NULL) {
					$value = '\''.$column['Default'].'\'';
				}
	
				$model['field'][$column['Field']] = array('value'=>$value, 'comment'=>$column['Comment']);
				if (strlen($column['Field']) > $maxlen) {
					$maxlen = strlen($column['Field']);
				}
			}
			//更新Orm类文件
			if (file_exists($file)) {
				//如果文件已经存在只做替换
				$phpfile   = file_get_contents($file);
				$phpfile   = preg_replace('/(\$table\s*=\s*\')([\w]*)(\')/', '$1'.$table.'$3', $phpfile);
				$phpfile   = preg_replace('/(\$orgtable\s*=\s*\')([\w]*)(\')/', '$1'.$table.'$3', $phpfile);
				$phpfile   = preg_replace('/(\$prikey\s*=\s*\')([\w]*)(\')/', '$1'.$model['prikey'].'$3', $phpfile);
				$phpfile   = preg_replace('/(\$reader\s*=\s*\')([\w]*)(\')/', '$1'.$model['reader'].'$3', $phpfile);
				$phpfile   = preg_replace('/(\$writer\s*=\s*\')([\w]*)(\')/', '$1'.$model['writer'].'$3', $phpfile);
				$phpfile   = preg_replace('/(\$dbinc\s*=\s*\')([\w]*)(\')/', '$1'.$dbinc.'$3', $phpfile);
				
				@unlink($file);
				file_put_contents($file, $phpfile);
				$modmodels[] = $file;
			} else {
				//否则需要重新生成页面
				$phpfile  = "<?php\r\n";
				$phpfile .= "namespace src\\model\\{$dbinc}\\{$segns};\r\n";
				$phpfile .= "class {$clsname} extends \classlib\core\model {\r\n";
				$phpfile .= "\tprotected \$table   = '$table';\r\n";
				$phpfile .= "\tprotected \$orgtable= '$table';\r\n";
				$phpfile .= "\tprotected \$prikey  = '{$model['prikey']}';\r\n";
				$phpfile .= "\tprotected \$reader  = '{$model['reader']}';\r\n";
				$phpfile .= "\tprotected \$writer  = '{$model['writer']}';\r\n";
				$phpfile .= "\tprotected \$dbinc   = '{$dbinc}';\r\n";
				$phpfile .= "}\r\n";
				file_put_contents($file, $phpfile);
				$newmodels[] = $file;
			}
			//更新Orm字段
			$file       = $fdir.'/'.$clsname.'.cls.php';
			@unlink($file);
			//否则需要重新生成页面
			$phpfile  = "<?php\r\n";
			$phpfile .= "return ".self::array2str($model['field'], $maxlen)."\r\n\r\n";
			$phpfile .= "\r\n";
			file_put_contents($file, $phpfile);
			$newmodels[] = $file;
		}
		echo '<br />新增的模型:<br />';
		echo implode("\r\n", $newmodels);
		echo '<br />更新的模型:<br />';
		echo implode("\r\n", $modmodels);
	}
	
	/**
	 * 格式化输出表字段信息
	 * @param array $arr
	 * @param int   $maxlen
	 * @return string
	 */
	public static function array2str($arr, $maxlen) {
		$items = array();
		$len   = count($arr);
		$i     = 0;
		foreach ($arr as $key=>$item) {
			$i++;
			if ($i == $len) {
				$items[] = sprintf("'%s'%s\t=> %s\t\t\t//%s", $key,
					 str_repeat(' ', $maxlen-strlen($key)), $item['value'], $item['comment']);
			} else {
				$items[] = sprintf("'%s'%s\t=> %s,\t\t\t//%s", $key, 
					str_repeat(' ', $maxlen-strlen($key)), $item['value'], $item['comment']);
			}
		}
		$str   = "array(\r\n\t\t".implode("\r\n\t\t", $items)."\r\n\t);";
		return $str;
	}
}